<script setup lang="ts">
import {
  getHomBannerApi,
  getHomeCategoryApi,
  getHomeHotApi,
  getHomeGuesssApi,
} from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import type { BannerItem, CategoryItem, HotItem, GuessItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { YxgGuessInstance } from '@/types/component'
// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomBannerApi()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryApi()
  categoryList.value = res.result
}

// 获取热门推荐数据
const homeHotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotApi()
  homeHotList.value = res.result
}
// 获取猜你喜欢组件实例
const guessRef = ref<YxgGuessInstance>()
// 滚动触底
const onScrolltolower = () => {
  console.log('底')
  guessRef.value?.getHomeGuesssData()
}

const isTriggered = ref(false)
// 下拉刷新被触发
const onRefresh = async () => {
  //开启刷新动画
  isTriggered.value = true
  //重置猜你喜欢组件数据
  guessRef.value?.resetData()
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotData()
  //加载数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getHomeGuesssData(),
  ])
  //关闭刷新动画
  isTriggered.value = false
}

// 页面加载
onLoad(() => {
  getHomeBannerData()
  getHomeCategoryData()
  getHomeHotData()
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresh"
    :refresher-triggered="isTriggered"
    class="scroolView"
    scroll-y
    @scrolltolower="onScrolltolower"
  >
    <!-- 自定义轮播图 -->
    <YxgSwiper :list="bannerList" />
    <!-- 分类面板 -->
    <CategoryPanel :list="categoryList" />
    <!-- 热门推荐 -->
    <HotPanel :list="homeHotList" />
    <!-- 猜你喜欢 -->
    <YxgGuess ref="guessRef" />
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
  .scroolView {
    flex: 1;
  }
}
</style>
